<template>
	<eui-page-frame topHeight="170" bottomHeight="96">
		<template #top>
			<view class="content-img">
				<eui-navbar ref="EuiNavBar" :title="title" color="#000000" backgroundColor="#FFFFFF">
				</eui-navbar> 
			</view>
		</template>
		<eui-page-content>
			<view class="card">
				<eui-card-input maxlength="10" v-model="mainData.c_name" title="费用名称" placeholder="请输入费用名称" type="text" />
				<eui-card-input v-model="mainData.c_amount" title="费用总额" placeholder="" type="number" displayable="true" />
				<eui-card-input v-model="mainData.c_inv_fee_rate" title="发票代开费率"
						type="radio" :range="payTaxRateDatas" />
				<eui-card-input v-model="mainData.c_status" title="状态" type="radio" 
				 :range="getDictSelectList('是否有效')" />
				<eui-card-input maxlength="100" v-model="mainData.c_desc" title="费用说明" placeholder="请输入费用说明" />
			</view>
			<view class="card" v-for="(item, index) in detailData" :key="index">
				<eui-card-input v-model="item.c_fee_name"   title="费用项目" displayable="true" />
				<eui-card-input v-model="item.c_fee_amount" title="费用金额" fieldName="c_fee_item"
					type="number" isBlur :itemIndex="index" @confirm="validateDetail"  maxlength="7" placeholder="请输入费用金额" />
				<eui-card-input isBlur maxlength="100" @confirm="validateDetail" :itemIndex="index" v-model="item.c_note" placeholder="请输入备注" title="备注" />
			</view>
		</eui-page-content>
		<template #bottom>
			<view class="bt-button">
				<eui-button type="primary" title="保存" @click="saveBill" />
			</view>
		
		</template>
	</eui-page-frame>  
</template>

<script setup type="ts">
	import { ref, reactive, onMounted } from 'vue';
	import {useMainStore} from "@/store/modules/store";
	import {useLoginStore} from "@/store/modules/useLoginStore";
	import { validateStores } from '@/hooks/useValidateMethod';
	import dateRangUtil from '../../../common/dateRangUtil';
	import { getRelatedName, getDictName,getDictSelectList, getDictSelect,getUserDictList } from '../components/RelatedName.js';
	import Enjoy from "@/common/enjoy";
	import {onLoad} from "@dcloudio/uni-app";
	import { init } from '@/hooks/init';
	import useService from '@/hooks/useService';
	import { initTaxRate, payTaxRateItems } from '@/hooks/useTaxRateHook';
	import dayjs from 'dayjs';
	const service = useService({ prefix: "bcApi" });
	const mainService = useService({ prefix: "mainApi" });
	const mainStore = useMainStore();
	const LoginStore = useLoginStore();
	const EuiNavBar = ref(null);
	const RdsSearchBar = ref(null);
	const { loginInfo } = mainStore;
	const searchText = ref('');
	const sUserStore = ref('');
	const sUserStoreName = ref('');
	const sUser = ref('');
	const c_no = ref('');
	const c_status = ref('0');
	const payTaxRateDatas = ref([]);
    const newList = ref([]);
    const modifiedList = ref([]);
    const delList = ref([]);
	const title = ref('采购费用方案');
    const mainData = ref({
                c_tenant_id: '',
                c_no: '',
                c_desc: '',
                c_status: '1',
                c_amount: 0,
                c_inv_fee_rate: '0.00',
                c_modify_userno: '',
                c_note: '',
            });
    const detailData = ref([]);

	onLoad(async (option) => {
		
		setDefault();
		await initTaxRate();
		
		payTaxRateDatas.value = payTaxRateItems.map(x=>{
			return {
				...x,
				value: parseFloat(x.value).toFixed(2).toString()
			}
		});

		c_no.value = option.c_no;
		if (option.c_no) {
		  title.value = option.c_no + '详情'
		  await billQuery();
		} else {
		  initFeeDict();
		}
	})
	const setDefault = () => {
		sUserStore.value = loginInfo.sUserStore;
		sUserStoreName.value = loginInfo.sUserStoreName;
		sUser.value = loginInfo.sUser;
		mainData.value.c_charge_userno = loginInfo.sUser;
	} 
	const initFeeDict = () => {
		const list = getUserDictList('生鲜采购费用')
		
		detailData.value = list.map(x => {
			return {
				c_fee_item: x.c_id,
				c_fee_amount: parseFloat(0).toFixed(2),
				c_fee_name: x.c_name,
			}
		});
	}
	 // 获取单据详情信息
	const billQuery = async() => {
		if (!c_no.value) {
			return;
		}
		const req = {
			BillId: c_no.value,
		};
		uni.showLoading({ title: "正在加载...", mask: true })
		const result = await service.request('采购费用方案维护', 'EnjoyBillQuery', req,'');
		uni.hideLoading(); 
		if (result.ds.length > 0) {
			mainData.value = result.ds[0];
			mainData.value.c_inv_fee_rate = mainData.value.c_inv_fee_rate.toFixed(2).toString()
			detailData.value = result.ds1;
			detailData.value.forEach(x => {
				x.c_fee_amount = parseFloat(x.c_fee_amount).toFixed(2);
				x.rowType = 0;
				x.c_fee_name=getDictName('生鲜采购费用',x.c_fee_item);
			})
			title.value = mainData.value.c_no + '详情'
		} else {
			uni.showToast({
				duration: 2000,
				icon: 'none',
				title: '未查询到数据',
				mask: true,
			});
		}
	}
	const validateMain = (args) => {
		const { type, fieldName, oldValue, newValue, itemIndex } = args;
		switch (fieldName) {
			case 'c_inv_fee_rate':
				mainData.value.c_inv_fee_rate = newValue;
				break;
		}
	}
	const validateDetail = (args) => {
		const { type, fieldName, oldValue, newValue, itemIndex } = args;
		const item = detailData.value[itemIndex];
		switch (fieldName) {
			case 'c_fee_item':
				if(newValue<0){
					uni.showToast({
						duration: 2000,
						icon: 'none',
						title: `费用项目[${item.c_fee_name}]的费用金额不能小于0`
					});
					item.c_fee_amount=parseFloat(0).toFixed(2);
					return;
				}
				if(newValue>999999){
					uni.showToast({
						duration: 2000,
						icon: 'none',
						title: `费用项目[${item.c_fee_name}]的费用金额不能大于999999`
					});
					item.c_fee_amount=parseFloat(0).toFixed(2);
					return;
				}
				item.c_fee_amount = parseFloat(newValue).toFixed(2);
				calcMainAmount();
				break;
		}
		item.rowType = (item.rowType === 1 || item.rowType === undefined) ? 1 : 2;
	}
	 const calcMainAmount = ()=> {
	    mainData.value.c_amount = detailData.value.reduce((pre, current) => pre + current.c_fee_amount * 1, 0).toFixed(2);
	}
	const saveBill = async() =>{
		let detailCheck = true;
		if (detailData.value.length <= 0) {
			uni.showToast({
				duration: 2000,
				icon: 'none',
				title: '请录入明细！'
			});
			return;
		}
		for (let i = 0; i < detailData.value.length; i++) {
			const item = detailData.value[i];
			if(item.c_fee_amount<0)
			{
				uni.showToast({
					duration: 2000,
					icon: 'none',
					title: `费用项目[${item.c_fee_name}]的费用金额不能小于0` 
				});
				return;
			}
		}
		// service.enjoyShowLoading('正在保存...');
		const flag = c_no.value;
		if (!c_no.value) {
			const getBilllIdReq = {
				BillIdKeyValue: {
					key: "c_no",
					value: ""
				},
				BillVariable: "",
				TableName: "tb_md_fsh_pur_fee_template",
				BillName: "采购费用方案维护"
			}
			const billlId = await mainService.request('单号生成服务', 'EnjoyGetBillId', getBilllIdReq,'');
			if (billlId) {
				c_no.value = billlId;
				mainData.value.c_no = billlId;
				mainData.value.c_mk_userno = sUser.value;
			}
		} else {
			mainData.value.c_no = c_no.value;
			mainData.value.c_modify_userno = sUser.value;
			mainData.value.c_modify_dt = dayjs().format('YYYY-MM-DD HH:mm:ss');
		}

		detailData.value.forEach(x => x.c_no = c_no.value)
		detailData.value.forEach(x=>{
			if(x.c_fee_amount<0){
				uni.showToast({
					duration: 2000,
					icon: 'none',
					title: `费用项目[${x.c_fee_name}]的费用金额不能小于0`
				});
				detailCheck=false;
				return;
			}
		})
		if(!detailCheck){
			return;
		}
		newList.value = detailData.value.filter(x => x.rowType == 1 || !x.hasOwnProperty('rowType'));
		modifiedList.value = detailData.value.filter(x => x.rowType == 2);
		const req = {
			NewList: flag ? [] : [mainData.value],
			ModifiedList: flag ? [mainData.value] : [],
			DelList: [],
			TableName: "tb_md_fsh_pur_fee_template",
			PrimaryKeys: ["c_tenant_id", "c_no"],
			ChildData: [{
				ChildTableName: "tb_md_fsh_pur_fee_detail_template",
				ParentTableName: "tb_md_fsh_pur_fee_template",
				ChildColumnNames: ["c_no"],
				ParentColumnNames: ["c_no"],
				ChildSaveModel: {
					NewList: newList.value,
					ModifiedList: modifiedList.value,
					DelList: delList.value,
					TableName: "tb_md_fsh_pur_fee_detail_template",
					PrimaryKeys: ["c_tenant_id", "c_no", "c_fee_item"]
				},
			}],
			BillSet: {
				BillIdKeyValue: {
					key: "c_no",
					value: c_no.value
				},
				BillVariable: "",
				TableName: "tb_md_fsh_pur_fee_template",
				BillName: "采购费用方案维护"
			}
		};
		uni.showLoading({ title: "正在保存...", mask: true })
		const result = await service.request('采购费用方案维护', 'EnjoyBillSaveNew', req,'');
		uni.hideLoading();
		uni.showToast({
			duration: 2000,
			icon: 'none',
			title: `保存成功`
		});
		newList.value = [];
		modifiedList.value = [];
		delList.value = [];
		await billQuery()
	}
</script>

<style lang="scss">
	.content {
		display: flex;
		flex: 1;
		flex-direction: column;
		background-color: #F2F2F2;
		padding: 0px !important
	}

	.content-img {
		background-color: #FFFFFF;
		// background-size: 100% 420rpx;
		// background-repeat: no-repeat;
		width: 100%;
	}

	.navigation {
		flex: 0 0 auto;
		margin-bottom: 5px;
	}
	.card {
		border-radius: 20rpx;
		padding:  20rpx 0rpx 20rpx 0rpx;
		margin-bottom: 20rpx;
		background: #ffffff;
	}
	.bt-button {
		background-color: #FFFFFF;
		padding: 10rpx 0rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
	}
</style>